package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.FriendMovement;
import com.itheima.domain.mongo.Movement;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MovementAsyncService {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveMovementFriend(Movement movement){
        try {
            Thread.sleep(3);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        //2. 查询好友列表
        //2-1 构建条件
        Query query = new Query(Criteria.where("userId").is(movement.getUserId()));
        //2-2 mongo查询
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //2-3遍历
        if(CollectionUtil.isNotEmpty(friendList)){
            for (Friend friend : friendList) {
                //2-4 获取好友id
                Long friendId = friend.getFriendId();
                //3.向好友添加我的动态
                //3-1 创建实体
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setUserId(movement.getUserId());//发布人id
                friendMovement.setPublishId(movement.getId());//动态id
                friendMovement.setCreated(movement.getCreated());//发布时间
                //3-2 保存好友动态
                mongoTemplate.save(friendMovement,ConstantUtil.MOVEMENT_FRIEND+friend);
            }
        }


    }
}
